
package greendbgui

import java.util.Set;

class ElectoralRollService 
{
    boolean transactional = true

    def getAllRolls()
    {
        return ElectoralRoll.list()
    }
    
    def getLatestRolls()
    {
        // really just want to be able to list the latest roll for each ward
        
        Map<Ward, ElectoralRoll> latest = new TreeMap<Ward, ElectoralRoll>()
        
        for (roll in getAllRolls())
        {
            if (!latest.containsKey(roll.ward))
            {
                latest.put (roll.ward, roll)
            }
            else
            {
                def existing = latest.get (roll.ward)
                
                if (roll.date > existing.date)
                {
                    latest.put (roll.ward, roll)
                }
            }
        }
        
        return latest.values()
    }
    
    def getEntries (electoralRoll, params) 
    {
        params.max = params?.max?.toInteger() ?: 1000
        params.offset = params?.offset?.toInteger() ?: 0
        params.sort = params?.sort ?: "id"
        params.order = params?.order ?: "asc"
 
        
        def entries = ElectoralRollEntry.createCriteria().list (max: params.max,
                                                                offset: params.offset,
                                                                sort: params.sort, 
                                                                order: params.order) 
        {
            createAlias ("person", "p")
            createAlias ("address", "a")
            and
            {
                eq "electoralRoll", electoralRoll
                
                and
                {
	                if (params?.name)
	                {
	                	or
	                	{
	                		ilike "p.surname", "%" + params.name + "%"
	                		ilike "p.firstNames", "%" + params.name + "%"
	                	}
	                } 
	                
	                if (params?.address)
	                {
	                	or
	                	{
	                		ilike "a.address1", "%" + params.address + "%"
	                		ilike "a.address2", "%" + params.address + "%"
	                		ilike "a.address3", "%" + params.address + "%"
	                		ilike "a.address4", "%" + params.address + "%"
	                		ilike "a.address5", "%" + params.address + "%"
	                	}
	                }
	            } 
            }
        }
        
//        return album.pictures().subList (from, to)
    }    
}
